﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using PhotoGallery.Models;
using PhotoGallery.Repositories;
using PhotoGallery.Utils;

namespace PhotoGallery.Controllers
{
    [Authorize]
    public class UserManagerController : Controller
    {
        private readonly ILogger<UserManagerController> _logger;
        private PhotoGalleryRepository _repo;
        private RoleModel _adminList;
        public UserManagerController(ILogger<UserManagerController> logger,
            RoleModel roles,
            PhotoGalleryRepository repo)
        {
            _logger = logger;
            _repo = repo;
            _adminList = roles;
        }
        // GET: UserManager
        public ActionResult Index(string msg = "")
        {
            List<User> model  = null;
            if (_adminList.Roles.Contains(this.User.Identity.Name))
            {
                model = _repo.Users.ToList();
            }
            else
            {
                model = _repo.Users.Where(w => w.UserName == User.Identity.Name).ToList();
            }
            if (!string.IsNullOrEmpty(msg))
            {
                ViewBag.Msg = msg;
            }
            return View(model);
        }

        // GET: UserManager/Details/5
        public ActionResult Details(int id)
        {
            var model = _repo.Users.FirstOrDefault(w => w.UId == id);
            return View(model);
        }

        // GET: UserManager/Create
        public ActionResult Create()
        {
            if (!_adminList.Roles.Contains(this.User.Identity.Name))
            {
                return RedirectToAction(nameof(Index),new { msg = "权限不足!"});
            }
            return View(new User() { CreateDate = DateTime.Now});
        }

        // POST: UserManager/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create(User user)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    ModelState.AddModelError("UserFromErr","填写错误");
                    return View(user);
                }
                if (string.IsNullOrEmpty(user.PasswdHash) || user.PasswdHash != user.Salt)
                {
                    ModelState.AddModelError("UserFromErr", "密码不匹配");
                    user.PasswdHash = user.Salt = "";
                    return View(user);
                }
                var usr = _repo.Users.FirstOrDefault(w => w.UserName.ToLower() == user.UserName.ToLower());
                if(usr != null)
                {
                    ModelState.AddModelError("UserFromErr", "用户名已存在!");
                    
                    return View(user);
                }

                user.CreateDate = DateTime.Now;
                var salt = LoginHelper.GenerateSalt(10);
                var passwdHash = LoginHelper.EncryptPassword(user.PasswdHash, salt);
                user.Salt = salt;
                user.PasswdHash = passwdHash;
                user.FailRetry = 0;
                _repo.Users.Add(user);
                _repo.SaveChanges();
                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: UserManager/Edit/5
        public ActionResult Edit(int id)
        {
            var model = _repo.Users.FirstOrDefault(w => w.UId == id);
            return View(model);
        }

        // POST: UserManager/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(int id, User user)
        {
            try
            {
                var usr = _repo.Users.FirstOrDefault(w => w.UId == id);
                if (usr == null)
                {
                    ModelState.AddModelError("UserFromErr", "用户名不存在!");

                    return View(user);
                }
                if (!ModelState.IsValid)
                {
                    ModelState.AddModelError("UserFromErr", "填写错误");
                    return View(user);
                }
                if (!_adminList.Roles.Contains(this.User.Identity.Name) && User.Identity.Name != usr.UserName)
                {
                    return RedirectToAction(nameof(Index), new { msg = "权限不足!" });
                }
                if (!string.IsNullOrEmpty(user.PasswdHash))
                {
                    if (user.PasswdHash != user.Salt)
                    {
                        ModelState.AddModelError("UserFromErr", "密码不匹配");
                        user.PasswdHash = user.Salt = "";
                        return View(user);
                    }
                    var salt = usr.Salt;
                    var passwdHash = LoginHelper.EncryptPassword(user.PasswdHash, salt);
                    usr.PasswdHash = passwdHash;

                }

                
                usr.UserName = user.UserName;
                usr.IsEnable = user.IsEnable;
                _repo.Users.Update(usr);
                _repo.SaveChanges();

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }

        // GET: UserManager/Delete/5
        public ActionResult Delete(int id)
        {
            var model = _repo.Users.FirstOrDefault(w => w.UId == id);
            return View(model);
        }

        // POST: UserManager/Delete/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Delete(int id, IFormCollection formCollection)
        {
            try
            {
               
               
                var usr = _repo.Users.FirstOrDefault(w => w.UId == id);
                if (usr == null)
                {     
                    return RedirectToAction(nameof(Index), new { msg = "用户不存在!" });
                }
                if (!_adminList.Roles.Contains(this.User.Identity.Name) && User.Identity.Name != usr.UserName)
                {
                    return RedirectToAction(nameof(Index), new { msg = "权限不足!" });
                }
                if (usr.UserName == "murry")
                {
                    return RedirectToAction(nameof(Index), new { msg = "该用户禁止删除!" });
                }
               
                _repo.Users.Remove(usr);
                _repo.SaveChanges();

                return RedirectToAction(nameof(Index));
            }
            catch
            {
                return View();
            }
        }
    }
}